import React, { useState, Suspense, lazy, useEffect } from "react";

import { useLocation } from "react-router-dom";

const load = (name: string): React.ReactElement => {
  let Component = lazy(() => import(`./${name}`));
  return <Component />;
};

const titleCase = (name: string): string => {
  return name.slice(0, 1).toUpperCase() + name.slice(1).toLowerCase();
};

export default function Content(props: MenuProps) {
  const [componentName, setComponentName] = useState("Create")
  const location = useLocation();
  const { permits } = props;
  const current = permits.find((p) => p.path === location.pathname);
  const children = permits.filter((p) => p.parentId === current?.id);

  useEffect(()=>{
    main()
  }, [location.pathname])

  const main = () => {
    if (!children || children.length === 0) {
      const name = location.pathname.substring(
        location.pathname.lastIndexOf("/") + 1
      );
      setComponentName(titleCase(name))
    } 
  };

  return (
    <Suspense fallback={<div>Loading...</div>}>
      {load(componentName)}
    </Suspense>
  )
}
